import syscall

int EI_MAG0 = 0
u8 ELFMAG0 = 0x7f

int EI_MAG1 = 1
u8 ELFMAG1 = 69 // 'E'

int EI_MAG2 = 2
u8 ELFMAG2 = 76 // 'L'

int EI_MAG3 = 3
u8 ELFMAG3 = 70 // 'F'

u16 EM_AARCH64 = 183 // arm64
u16 EM_ARM = 40 // armv7 and armv6
u16 EM_RISCV = 243 // riscv64
u16 EM_X86_64 = 62 // amd64
u16 EM_386 = 3 // i386

type elf64_ehdr_t = struct {
    arr<u8,16> ident
    u16 type
    u16 machine
    u32 version
    u64 entry
    u64 phoff
    u64 shoff
    u32 flags
    u16 ehsize
    u16 phentsize
    u16 phnum
    u16 shentsize
    u16 shnum
    u16 shstrndx
}

fn arch(string path):string {
    if path == '' {
        throw 'path is empty'
    }

    int fd = syscall.open(path, syscall.O_RDONLY, 0)

    var elf_header = elf64_ehdr_t{}
    syscall.read(fd, elf_header as cptr, sizeof(elf64_ehdr_t))
    syscall.close(fd)

    if elf_header.ident[EI_MAG0] != ELFMAG0 ||
       elf_header.ident[EI_MAG1] != ELFMAG1 ||
       elf_header.ident[EI_MAG2] != ELFMAG2 ||
       elf_header.ident[EI_MAG3] != ELFMAG3 {

       throw 'not a valid elf file'
    }

    // 读取常用的 arch 并解析成字符串返回
    {u16:string} arch_of = {
        EM_AARCH64: 'arm64',
        EM_ARM: 'armv7',
        EM_RISCV: 'riscv64',
        EM_X86_64: 'amd64',
        EM_386: 'i386'
    }

    var arch = arch_of[elf_header.machine]

    return arch
}